﻿Imports Com.SharpZebra
Imports Com.SharpZebra.Printing
Imports System.Text.RegularExpressions
Imports System.Text
Imports System.Globalization
Imports System.Windows.Forms

Module PullEmailClass

    Dim printer As ZebraPrinters = New ZebraPrinters()
    Private Declare Auto Function AllocConsole Lib "kernel32.dll" () As Boolean
    Sub Main()
        Dim args() As String = Environment.GetCommandLineArgs()
        If args.Length > 1 Then
            '--- Yep, create the console window and run the console mode logic
            AllocConsole()
            ConsoleMain(args)
        Else
            '--- Nope, run the normal Windows Forms startup code
            Application.EnableVisualStyles()
            Application.SetCompatibleTextRenderingDefault(False)
            Application.Run(New ConfigureZebraLabelPrinting)
        End If


    End Sub

    Private Sub ConsoleMain(ByVal args() As String)
        '--- This code runs when command line arguments were given
        Try
            Dim client As ImapX.ImapClient = New ImapX.ImapClient(My.Settings.ImapServer, My.Settings.ImapServerPort, True)
            Dim result As Boolean = False
            result = client.Connection()

            If result Then
                Console.WriteLine("@Connected")
            End If

            result = client.LogIn(My.Settings.EmailUserName, My.Settings.EmailPassword)

            If result Then
                Console.WriteLine("@Logged in")
            End If

            Dim folders As ImapX.FolderCollection = client.Folders
            Dim mc = client.Folders("INBOX").Messages.Where(Function(x) x.Flags.Count = 0)


            For Each m As ImapX.Message In client.Folders("INBOX").Search("UNSEEN", True)
                m.Process()

                Dim textBody() As String = m.TextBody.TextData.Split(ControlChars.Lf) 'StripTags(m.HtmlBody.TextData).Split(ControlChars.Lf)

                'Print the label
                CommonClass.printLabel(textBody)

                'mark email as read
                m.SetFlag(ImapX.ImapFlags.SEEN)
            Next
        Catch ex As Exception
            CommonClass.WriteToEventLog(ex.Message.ToString & ControlChars.Lf & ControlChars.Lf & If(Not ex.InnerException Is Nothing, ex.InnerException.ToString, "No inner exception noted."))
            'MsgBox("Error encountered while trying to extract email or printing the label" & ControlChars.Lf & ControlChars.Lf & ex.Message.ToString, MsgBoxStyle.Critical, "Zebra Label Printer Failed")
        End Try
    End Sub

   

    'Sub printLabel(textString() As String)
    '    Dim sb As StringBuilder
    '    Dim sbLowerTag As StringBuilder

    '    sbLowerTag = New StringBuilder
    '    sb = New StringBuilder

    '    Dim appendToLowerTag As Boolean = True

    '    Try
    '        sb.AppendLine()
    '        sb.AppendLine("N") ' clear 
    '        sb.AppendLine("ZB") 'ZT - print orientation
    '        sb.AppendLine("q" & My.Settings.LabelWidth * 203) '3 7/8 inch x 203 dpi = 786.625 width
    '        sb.AppendLine("Q" & My.Settings.LabelLength * 203 & ",26") ' 8 inch x 203 dpi = 1624 length - 26 dot gap between labels, printer should detect this automatically
    '        sb.AppendLine("D" & My.Settings.Density) 'print density

    '        Dim txtSeparatorString As String = My.Settings.separatorString
    '        Dim textWrapCtr As Integer = My.Settings.textWrapCtr
    '        Dim xCoord As Integer = My.Settings.xcoord

    '        Dim yCoord As Integer = My.Settings.ycoord
    '        Dim yCoordAppend As Integer = My.Settings.yCoordAppend
    '        Dim topLabelFont As Integer = My.Settings.TopPartFont

    '        Dim origyCoordLowerTag As Integer = My.Settings.yCoordLowerTag
    '        Dim yCoordLowerTag As Integer = My.Settings.yCoordLowerTag
    '        Dim yCoordLowerAppend As Integer = My.Settings.yCoordLowerAppend
    '        Dim lowerLabelFont As Integer = My.Settings.LowPartFont

    '        Dim emailSeparatorFound As Boolean = False

    '        Dim textWrapping As List(Of String)

    '        For Each item In textString
    '            'Check for separator string to stop populating the stringbuilder that prints the lower part of the label
    '            'If separator string is encountered then stop populating the stringbuilder for printing of the lower label
    '            'any text (including the separator) after should not be printed on the lower part
    '            If item.ToString.Contains(txtSeparatorString) Then
    '                appendToLowerTag = False
    '                emailSeparatorFound = True
    '            End If

    '            'wrap text if necessary
    '            textWrapping = WrapText(Trim(item.ToString), textWrapCtr)
    '            If textWrapping.Count > 1 Then
    '                For Each lineItem In textWrapping
    '                    If yCoord < origyCoordLowerTag - 150 Then
    '                        sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "A" & xCoord & "," & yCoord & ",0," & topLabelFont & ",1,1,N,""" & lineItem.ToString & """"))
    '                        yCoord += yCoordAppend
    '                    End If

    '                    If appendToLowerTag Then
    '                        sbLowerTag.AppendLine(String.Format(CultureInfo.InvariantCulture, "A" & xCoord & "," & yCoordLowerTag & ",0," & lowerLabelFont & ",2,2,N,""" & lineItem.ToString & """"))
    '                        yCoordLowerTag += yCoordLowerAppend
    '                    End If
    '                Next
    '            Else
    '                If yCoord < origyCoordLowerTag - 150 Then
    '                    sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "A" & xCoord & "," & yCoord & ",0," & topLabelFont & ",1,1,N,""" & Trim(item.ToString) & """"))
    '                    yCoord += yCoordAppend
    '                End If

    '                If appendToLowerTag Then
    '                    sbLowerTag.AppendLine(String.Format(CultureInfo.InvariantCulture, "A" & xCoord & "," & yCoordLowerTag & ",0," & lowerLabelFont & ",2,2,N,""" & item.ToString & """"))
    '                    yCoordLowerTag += yCoordLowerAppend
    '                End If
    '            End If
    '        Next
    '        sb.Append(sbLowerTag.ToString)
    '        sb.AppendLine("P1, 1") ' print labels - 1 copy

    '        If Not emailSeparatorFound Then 'throw error, the separator string was not found inside the email body
    '            Throw New Exception("Email body separator not found. Please check label printer configuration.")
    '        End If

    '        Dim selectedPrinterName As String = DefaultPrinterName() 'printer.DefaultZebraPrinter()
    '        Dim z As New ZebraPrinter(selectedPrinterName)
    '        z.Print(sb.ToString)
    '    Catch ex As Exception
    '        WriteToEventLog(ex.Message.ToString & ControlChars.Lf & ControlChars.Lf & If(Not ex.InnerException Is Nothing, ex.InnerException.ToString, "No inner exception noted."))
    '    End Try
    'End Sub


   

    
End Module
